package com.jcfy.project.module.client;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.jcfy.framework.base.ClientBaseController;
import com.jcfy.framework.base.Error;
import com.jcfy.framework.web.domain.AjaxResult;
import com.jcfy.project.module.domain.TUser;
import com.jcfy.project.module.service.ITUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户信息Controller
 *
 * @author jiangfeng
 * @date 2020-08-13
 */
@Api("用户信息")
@RestController
@RequestMapping("/client/user")
public class UserController extends ClientBaseController {

    @Autowired
    private ITUserService tUserService;
    @Autowired
    private WxMaService wxMaService;

    /**
     * 用户管理-详情
     *
     * @param userId
     * @return
     */
    @ApiOperation("用户管理-详情")
    @PostMapping("/detail")
    public AjaxResult detail(Long userId) {
        try {
            TUser user = tUserService.selectTUserById(userId);
            return AjaxResult.success(user);
        } catch (Exception e) {
            logger.error("[用户管理-详情][状态#异常][原因# {}]", e.getMessage());
            return AjaxResult.error(Error._100000, e.getMessage());
        }
    }

    /**
     * 登录
     *
     * @param code
     * @param encryptedData
     * @param iv
     * @param rawData
     * @param signature
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(String code, String encryptedData, String iv, String rawData, String signature) {
        try {
            logger.info(code);
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();
            String sessionKey = sessionInfo.getSessionKey();
            String unionid = sessionInfo.getUnionid();
            logger.info(sessionInfo.toString());

            TUser user = new TUser();
            user.setMiniOpenid(openid);
            List<TUser> tUser = tUserService.selectTUserList(user);
            if (CollectionUtils.isNotEmpty(tUser)) {
                /**
                 * 已有
                 */
                user = tUser.get(0);
            } else {
                /**
                 * 没有，返回openId,开始获取用户信息
                 */
                // 用户信息校验
                if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
                    return AjaxResult.error("用户信息校验失败");
                }

                // 解密用户信息
                WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
                logger.info("userInfo: {}", userInfo.toString());

                user.setNickName(userInfo.getNickName());
                user.setUserIcon(userInfo.getAvatarUrl());
                user.setSex(Integer.parseInt(userInfo.getGender()));
                int i = tUserService.insertTUser(user);
                if (i <= 0) {
                    logger.error("[创建团购订单][状态# 失败][原因# 添加失败]");
                    return AjaxResult.error(Error._200211, "注册用户失败");
                }
            }
            String token = this.setSessionUser(user);
            logger.info("user: {}" + user.toString());
            System.out.println(user);
            user.setToken(token);
            return AjaxResult.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[创建团购订单][状态# 失败][原因# {}]", e.getMessage());
            return AjaxResult.error(Error._100000, e.getMessage());
        }
    }

    /**
     * 用户管理-设置缓存中用户信息
     *
     * @param userId
     * @return
     */
    @ApiOperation("用户管理-设置缓存中用户信息")
    @PostMapping("/setStorageUser")
    public AjaxResult setStorageUser(Long userId) {
        try {
            TUser user = tUserService.selectTUserById(userId);
            String token = this.setSessionUser(user);
            user.setToken(token);
            return AjaxResult.success(user);
        } catch (Exception e) {
            logger.error("[用户管理-设置缓存中用户信息][状态#异常][原因# {}]", e.getMessage());
            return AjaxResult.error(Error._100000, e.getMessage());
        }
    }

}
